/*
 * File Name:               XPropertyBingderMgr.cs
 *
 * Description:             属性绑定接口的管理类
 * Author:                  lisiyu
 * Create Date:             2016/06/27
 */

using System;
using System.Collections.Generic;

public class XPropertyBingderMgr : ICache
{
    private List<IPropertybinder> mPropertyUnbinders;

    public void onSpawn(object args)
    {
        if (mPropertyUnbinders == null)
            mPropertyUnbinders = new List<IPropertybinder>();
    }

    public void onRecycle()
    {
        unbindProperties();
    }

    /// <summary>
    /// 绑定属性事件 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="property"></param>
    /// <param name="callback"></param>
    /// <returns> 返回一个 IPropertybinder 接口 用于手动解绑之类的操作 </returns>
    public IPropertybinder bindProperty<T>(XProperty<T> property, Action<T> callback, bool callOnFirst = true)
    {
        if (property == null || callback == null) return null;

        var ret = XCachePool.Singleton.pop<XPropertyBinder<T>>(new XPropertyBinder<T>.Argument() { property = property, callback = callback });
        ret.bind(callOnFirst);
        mPropertyUnbinders.Add(ret);

        return ret;
    }

    /// <summary>
    /// 解绑全部属性事件 
    /// </summary>
    public void unbindProperties()
    {
        for (int i = 0; i < mPropertyUnbinders.Count; i++)
        {
            XCachePool.Singleton.push(mPropertyUnbinders[i]);
        }
        mPropertyUnbinders.Clear();
    }
}